<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/8/9
 * Time: 11:22
 */

namespace app\index\controller;


use app\api\model\Approval;
use EasyWeChat\ShakeAround\Page;
use think\Db;
use think\Request;
use think\Cache;
use foxyZeng\huyi\HuYiSMS;
use think\Exception;
use app\index\model\Jpush;
use app\index\model\Pdf;

class Order extends Backend
{

    /**
     * 订单列表   一共24个  付完定金24 个     付完中期款5个    已经付完尾款0个 查的都是以付款时间为准的
     */
    public function index()
    {

        $user         = $this->check_authority();
        $relation     = db('relation')->where('user_id', $user['admin_id'])->find();
        $node         = db('role')->where('id', $relation['role_id'])->find();
        $data         = Request::instance()->get();
      
        $data['type'] = isset($data['type']) ? $data['type'] : $data['type'];
        Cache::set('type', $data['type']);
        $model = db('order')
            ->alias('a')
            ->field('a.*,b.title,p.province,c.city,u.county,us.username as namekl,us.ce,st.store_name,co.dep_money,st1.dep,be.tail,co.weixin,cy.residential_id,cy.management,re.content as content1')
            ->join('chanel b', 'a.channel_id=b.id', 'left')
            ->join('province p', 'a.province_id=p.province_id', 'left')
            ->join('city c', 'a.city_id=c.city_id', 'left')
            ->join('county u', 'a.county_id=u.county_id', 'left')
            ->join('user us', 'a.assignor=us.user_id', 'left')
            ->join('store st', 'st.store_id=us.store_id', 'left')
            ->join('contract co', 'a.contract_id=co.contract_id', 'left')
            ->join('startup st1', 'a.startup_id=st1.startup_id', 'left')
            ->join('before be', 'a.before_id=be.before_id', 'left')
            ->join('community cy', 'a.order_id=cy.id', 'left')
            ->join('residential re', 're.residential_id=cy.residential_id', 'left');
        if (isset($data['status']) && $data['status'] != '') {

            $model->where(['a.state' => $data['status']]);
        }
        if (isset($data['start_time']) && $data['start_time'] != '' && isset($data['end_time']) && $data['end_time'] != '') {
            $model->where(['a.created_time' => ['between', [strtotime($data['start_time']), strtotime($data['end_time']) + 24 * 3600]]]);
        }
        if (isset($data['contacts']) && $data['contacts'] != '') {
            if (empty($data['chen'])) {
                $this->error('请输入搜索名称');
            }

            $model->where(['a.' . $data['chen'] . '' => ['like', "%{$data['contacts']}%"]]);
        };

        if (isset($data['assignor']) && $data['assignor'] != '') {
            $title = db('user')->where(['username' => ['like', "%{$data['assignor']}%"]])->field('user_id')->select();

            $s = '';
            foreach ($title as $key => $val) {
                $s .= $val["user_id"] . ',';
            }
            $s = substr($s, 0, -1);

            $model->where(['a.assignor' => ['in', $s]]);
        };

        if (empty($data['status']) && empty($data['order_no'])) {
            if ($data['type'] == 6) {
                $model->where(['a.state' => 7, 'product_id' => ['<>', 0]]);
            } elseif ($data['type'] == 7) {

                $model->where(['a.state' => $data['type'], 'product_id' => ['EQ', 0]]);
            } elseif ($data['type'] == 5) {
                $model->where(['a.state' => ['between', [4, 5]]])->order('a.order_id desc');
            } elseif (isset($data['type']) && $data['type'] != '') {

                $model->where(['a.state' => $data['type']]);
            }
        }
        if ($node['rule'] != '*') {
            if (!empty($user['store_id'])) {
                $title = db('user')->where(['store_id' => $user['store_id']])->field('user_id')->select();
                $s     = '';
                foreach ($title as $key => $val) {
                    $s .= $val["user_id"] . ',';
                }
                $s = substr($s, 0, -1);
                $model->where(['a.assignor' => ['in', $s]]);
            }
            if (!empty($user['qu'])) {
                $model->where(['a.channel_id' => ['in', $user['qu']]]);
            }
            if (!empty($user['residential_id'])) {
                $title = db('community')->where(['residential_id' => ['in', $user['residential_id']]])->field('id')->select();
                if ($title) {
                    $s2 = '';
                    foreach ($title as $key => $val) {
                        $s2 .= $val["id"] . ',';
                    }
                    $s2 = substr($s2, 0, -1);

                    $model->where(['a.order_id' => ['in', $s2]]);

                } else {

                    $model->where(['a.order_id' => 0]);
                }
            }
        }


        $list  = $model->order('a.order_id desc')
            ->paginate(20)
            ->each(function ($item, $key) {
                $thro = db('through')->where(['order_ids' => $item['order_id'], 'baocun' => 1])->order('th_time desc')->find();
                if ($thro['baocun'] == 1) {
                    $p = $thro['amount'];
                } else {
                    if ($item['ification'] == 2) {
                        $cap = db('capital')->where(['ordesr_id' => $item['order_id'], 'types' => 1, 'enable' => 1])->sum('to_price');
                        $ca  = db('envelopes')->where(['ordesr_id' => $item['order_id']])->field('give_money')->find();
                        $p   = $cap - $ca['give_money'];
                    } else {
                        $ca = db('capital')->where(['ordesr_id' => $item['order_id'], 'types' => 1, 'enable' => 1])->field('sum(to_price),sum(give_money)')->find();
                        $p  = $ca['sum(to_price)'] - $ca['sum(give_money)'];
                    }
                }

                $item['yu'] = 0;
                if (!empty($item['dep_money']) || $item['dep_money'] == 0) {
                    $item['yu'] = $p - $item['dep_money'];
                }
                if (!empty($item['dep']) && !empty($item['dep_money'])) {
                    $item['yu'] = $p - $item['dep_money'] - $item['dep'];
                }

                if (!empty($item['dep']) && !empty($item['dep_money']) && !empty($item['tail'])) {
                    $item['yu'] = $p - $item['dep_money'] - $item['dep'] - $item['tail'];
                }
                $cash   = 0;
                $WeChat = 0;

                if ($item['yu'] > 0) {
                    $pa = db('payment')->where(['orders_id' => $item['order_id']])->select();
                    if ($pa) {
                        foreach ($pa as $kl) {
                            if ($kl['weixin'] == 1) {
                                $cash += $kl['money'];
                            }
                            if ($kl['weixin'] == 2 && $kl['success'] == 2) {
                                $WeChat += $kl['money'];
                            }
                        }
                    }

                    if (!empty($cash)) {
                        $item['yu'] = $item['yu'] - $cash;
                        $item['yu'] = round($item['yu'], 3);
                    }
                    if (!empty($WeChat)) {
                        $item['yu'] = $item['yu'] - $WeChat;
                        $item['yu'] = round($item['yu'], 3);
                    }


                }

                $item['states'] = $this->type($item['state']);
                return $item;


            });
        $title = $this->type($data['type']);
        return $this->fetch('index', ['list' => $list, 'title' => $title, 'type' => $data['type'], 'hide' => $user['hide']]);
    }

    /**
     * 订单添加
     */
    public function add()
    {
        if ($data = Request::instance()->post()) {
            if (empty($data['addres'])) {
                return json_data([], 300, '请输入详细地址');
            }
            $user = [
                'channel_id'           => $data['channel_id'],//渠道
                'order_no'             => order_sn(),//渠道
                'pro_id'               => $data['pro_id'],//一级问题
                'pro_id1'              => $data['pro_id1'],//二级问题
                'pro_id2'              => $data['pro_id2'],//三级问题
                'province_id'          => $data['province'],//省
                'city_id'              => $data['city'],//市
                'county_id'            => $data['area'],//区
                'addres'               => $data['addres'],//地址
                'contacts'             => $data['contacts'],//联系人
                'telephone'            => trim($data['telephone']),//联系电话
                'remarks'              => $data['remarks'],//联系电话
                'logo'                 => !empty($data['logo']) ? serialize($data['logo']) : '',//联系电话
                'state'                => $data['state'],//待指派
                'residential_quarters' => $data['residential_quarters'],//小区名称
                'created_time'         => !empty($data['created_time']) ? strtotime($data['created_time']) : time(),//创建时间
            ];

            $res  = db('order')->insertGetId($user);
            $user = $this->check_authority();
            $t    = [
                'mode'      => '电话',
                'order_ids' => $res,
                'baocun'    => 0,
                'role'      => 1,
                'admin_id'  => $user['admin_id'],
                'status'    => $this->remo($data['status']),
                'status1'   => $this->remo($data['status1']),
                'status2'   => $this->remo($data['status2']),
                'th_time'   => time(),
                'end_time'  => strtotime($data['start_time']),
                'single'    => 0,
            ];
            $s1   = db('through')->insertGetId($t);
            if (!empty($data['residential_id'])) {
                $s1 = db('community')->insertGetId([
                    'id'             => $res,
                    'residential_id' => $data['residential_id'],
                    'management'     => $data['management'],

                ]);
            }
            db('order')->where(['order_id' => $res])->update(['through_id' => $s1, 'update_time' => time()]);
            $this->log('添加了一个订单', $res);
//             if($data['state']==10){
//                 vendor('foxyzeng.huyi.HuYiSMS');
//                 $sms=new HuYiSMS();
//                 $content ="亲，我们已经收到您在益鸟的订单，很抱歉，您所在的区域或服务暂时不能提供。你可关注“益鸟维修”公众号，随时可了解居家房屋妙招，若有问题可随时致电：4000987009，回T退订【益鸟维修】";
//                 $sms->duan($data['telephone'],$content);
//             }


            if ($res) {
                return json_data([], 200, '新增成功');
            }
            return json_data([], 300, '新增失败');
        }
        $chanel = db('chanel')->where('type', 1)->select();
        $go     = db('goods_category')->where(['pro_type' => 1, 'is_enable' => 1, 'parent_id' => 0, 'type' => 1])->select();
        $remote = db('remote')->where(['is_enable' => 1, 'parent_id' => 0])->field('id,title')->select();
        $title  = db('residential')->select();
        return $this->fetch('add', ['chanel' => $chanel, 'go' => $go, 'remote' => $remote, 'title' => $title]);
    }

    /**
     * 修改
     */
    public function edit($order_id = 0)
    {

        if ($data = Request::instance()->post()) {
            $data['logo'] = !empty($data['logo']) ? $data['logo'] : '';
            if (empty($data['addres'])) {
                return json_data([], 300, '请输入详细地址');
            }
            $user = [
                'channel_id'           => $data['channel_id'],//渠道
                'pro_id'               => $data['pro_id'],//一级问题
                'pro_id1'              => $data['pro_id1'],//一级问题
                'pro_id2'              => $data['pro_id2'],//一级问题
                'province_id'          => $data['province_id'],//省
                'city_id'              => $data['city_id'],//市
                'county_id'            => $data['county_id'],//区
                'addres'               => $data['addres'],//地址
                'contacts'             => $data['contacts'],//联系人
                'telephone'            => trim($data['telephone']),//联系电话
                'remarks'              => $data['remarks'],//备注
                'logo'                 => !empty($data['logo']) ? serialize($data['logo']) : '',//联系电话
                'update_time'          => time(),//创建时间
                'residential_quarters' => $data['residential_quarters'],//小区名称
                'created_time'         => !empty($data['created_time']) ? strtotime($data['created_time']) : time(),//创建时间
            ];
            $res  = db('order')->where(['order_id' => $data['order_id']])->update($user);
            if (!empty($data['residential_id'])) {
                $community = db('community')->where(['id' => $data['order_id']])->find();

                if ($community) {
                    db('community')->where('id', $data['order_id'])->update([
                        'residential_id' => $data['residential_id'],
                        'management'     => $data['management'],
                    ]);
                } else {
                    db('community')->insertGetId([
                        'id'             => $data['order_id'],
                        'residential_id' => $data['residential_id'],
                        'management'     => $data['management'],

                    ]);
                }

            }
            $this->log('修改了一个订单', $data['order_id']);

            if ($res !== false) {
                return json_data([], 200, '编辑成功');
            }
            return json_data([], 300, '编辑失败');
        } else {
            if (!$order_id) {
                $this->error('请刷新后重试');
            }
            $res = db('order')
                ->field('order.*,b.*,p.province_id,p.province,p.country_id,c.*,u.*,co.*,cy.management,cy.residential_id,re.content as content1')
                ->join('chanel b', 'order.channel_id=b.id', 'left')
                ->join('province p', 'order.province_id=p.province_id', 'left')
                ->join('city c', 'order.city_id=c.city_id', 'left')
                ->join('county u', 'order.county_id=u.county_id', 'left')
                ->join('contract co', 'order.contract_id=co.contract_id', 'left')
                ->join('community cy', 'order.order_id=cy.id', 'left')
                ->join('residential re', 're.residential_id=cy.residential_id', 'left')
                ->where(['order_id' => $order_id])
                ->find();
            $s   = db('goods_category')->where(['id' => $res['pro_id'], 'pro_type' => 1])->find();
            $s1  = db('goods_category')->where(['id' => $res['pro_id1'], 'pro_type' => 1])->find();
            $s2  = db('goods_category')->where(['id' => $res['pro_id2'], 'pro_type' => 1])->find();

            $res['pro_ids']  = !empty($s['title']) ? $s['title'] : '暂无数据';
            $res['pro_ids1'] = !empty($s1['title']) ? $s1['title'] : '暂无数据';
            $res['pro_ids2'] = !empty($s2['title']) ? $s2['title'] : '暂无数据';

            $res['states'] = $this->type($res['state']);
            if ($res['logo']) {
                $res['logo'] = unserialize($res['logo']);
            }
            if (!$res) {
                $this->error('用户不存在或已删除');
            };

            $chanel = db('chanel')->where('type', 1)->select();
            $go     = db('goods_category')->where(['pro_type' => 1, 'is_enable' => 1, 'parent_id' => 0, 'type' => 1, 'id' => ['neq', $res['pro_id']]])->select();
            $title  = db('residential')->select();
            return $this->fetch('edit', ['res' => $res, 'chanel' => $chanel, 'go' => $go, 'title' => $title]);
        }
    }

    /**
     * 沟通记录修改
     */
    public function through()
    {

        if ($data = Request::instance()->post()) {
    
            $t = [
                'mode'     => $data['mode'],
                'remar'    => $data['remar'],
                'status'   => isset($data['status'])?$this->remo($data['status']):'',
                'status1'  => isset($data['status1'])?$this->remo($data['status1']):'',
                'status2'  => isset($data['status2'])?$this->remo($data['status2']):'',
                'th_time'  => strtotime($data['start_time']),
                'end_time' => strtotime($data['end_time']),
    
            ];

            $res = db('through')->where('through_id', $data['through_id'])->update($t);
            $this->log('修改了沟通记录', $data['order_ids']);
            if ($res !== false) {
                return json_data([], 200, '编辑成功');
            }
            return json_data([], 300, '编辑失败');
        }
        $through_id = Request::instance()->get('through_id');
        $type       = Request::instance()->get('type');
        if (!$through_id) {
            $this->error('请刷新后重试');
        }
        $res = db('through')
            ->where(['through_id' => $through_id])
            ->find();

        $remote = db('remote')->where(['is_enable' => 1, 'parent_id' => 0])->field('id,title')->select();
        $rem    = db('remote')->where(['is_enable' => 1, 'title' => $res['status']])->field('id')->find();

        $go1 = db('remote')->where(['is_enable' => 1, 'parent_id' => $rem['id']])->select();
        $rm  = db('remote')->where(['is_enable' => 1, 'title' => $res['status1']])->field('id')->find();

        $go2 = db('remote')->where(['is_enable' => 1, 'parent_id' => $rm['id']])->select();
        return $this->fetch('through', ['res' => $res, 'remote' => $remote, 'go1' => $go1, 'go2' => $go2, 'type' => $type]);

    }

    /**
     * 取消
     */
    public function del()
    {
        $store_id = Request::instance()->post();
        $res      = false;
        if ($store_id['re'] == 1) {
            $o = implode(",", $store_id['arr']) . ',' . $store_id['reason'];
        } else {
            $o = $store_id['reason'];
        }

        if ($store_id) {
            $res = db('order')->where(['order_id' => $store_id['order_id']])->update(['state' => 8, 'reason' => $o, 'tui_time' => time()]);

            $this->log('取消订单', $store_id['order_id']);
        }
        if ($res !== false) {
            return json_data([], 200, '取消成功');
        }
        return json_data([], 300, '取消失败');
    }

    /**
     * 退单
     */
    public function tui()
    {
        $store_id = Request::instance()->post();
        if ($store_id['re'] == 1) {
            $o = implode(",", $store_id['arr']) . ',' . $store_id['reason'];
        } else {
            $o = $store_id['reason'];
        }
        $res = false;
        if ($store_id) {
            $res = db('order')->where(['order_id' => $store_id['order_id']])->update(['state' => 9, 'reason' => $o, 'tui_moey' => $store_id['tui_moey'], 'tui_state' => 1, 'tui_time' => time()]);

            $this->log('退单', $store_id['order_id']);
        }
        if ($res !== false) {
            return json_data([], 200, '取消成功');
        }
        return json_data([], 300, '取消失败');
    }

    /**
     * 删除基建
     */
    public function del1()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        $res1  = db('capital')->where(['capital_id' => $data['capital_id']])->field('ordesr_id')->find();
        $order = db('order')->where('order_id', $res1['ordesr_id'])->field('ification')->find();
        if ($order['ification'] == 2) {
            db('capital')->where(['capital_id' => $data['capital_id']])->update(['types' => 2]);
        } else {
            $capital = db('capital')->where(['capital_id' => $data['capital_id'], 'types' => 1])->field('give_money')->find();
            if ($capital['give_money'] != 0) {
                db('capital')->where(['capital_id' => $data['capital_id']])->update(['types' => 2]);
                $capital_id = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1])->field('capital_id')->order('capital_id desc')->find();
                db('capital')->where(['capital_id' => $capital_id['capital_id']])->update(['give_money' => $capital['give_money']]);
            } else {
                db('capital')->where(['capital_id' => $data['capital_id']])->update(['types' => 2]);
            }
        }
        $pdf = new Pdf();
        $pdf->put($res1['ordesr_id'], 1);
        $uss['store_code_id'] = $data['capital_id'];
        $da                   = send_post(UIP_SRC . "/shopowner/Order/delOrderProblem", $uss);
        $results              = json_decode($da);
        if ($results->code != 200) {
            db()->rollback();
            return json_data([], 200, '成功');
        }
        db()->commit();
        return json_data([], 200);
    }

    /**
     * 删除远程基建
     */
    public function del2()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $res1 = db('capital')->where(['capital_id' => $data['capital_id'], 'types' => 1])->field('ordesr_id,give_money')->find();
            if (empty($res1)) {
                return json_data('订单有误', 300);
            }
            db('capital')->where(['capital_id' => $data['capital_id']])->update(['types' => 2]);


            $uss['store_code_id'] = $data['capital_id'];
            $da                   = send_post(UIP_SRC . "/shopowner/Order/delOrderProblem", $uss);
            $results              = json_decode($da);
            if ($results->code != 200) {
                db()->rollback();
                return json_data([], 200, '成功');
            }
            $WeChat = 0;
            $s      = '';
            $re     = db('capital')->where(['ordesr_id' => $res1['ordesr_id'], 'enable' => 1, 'programme' => 3, 'types' => 1])->field('capital_id,to_price')->select();
            foreach ($re as $item) {
                $WeChat += $item['to_price'];
                $s      .= $item["capital_id"] . ',';
            }
            $s = substr($s, 0, -1);
            db('through')->where(['order_ids' => $res1['ordesr_id'], 'baocun' => 1])->update(['amount' => $WeChat, 'capital_id' => $s]);
            $this->log('删除远程基建', $res1['ordesr_id']);
            db()->commit();
            return json_data([], 200);
        } catch (Exception $e) {
            db()->rollback();
            return json_data([], 300, $e->getMessage());
        }

    }

    /**
     * 审核
     */
    public function shen()
    {
        $store_id = Request::instance()->post();

        $res = false;
        if ($store_id) {
            $res = db('order')->where(['order_id' => $store_id['order_id']])->update(['tui_state' => 2, 'tui_shen' => $store_id['tui_shen']]);
            $this->log('审核', $store_id['order_id']);
        }
        if ($res !== false) {
            return json_data([], 200, '审核成功');
        }
        return json_data([], 300, '审核失败');
    }

    /**
     * 开工设置
     */
    public function she($order_id)
    {

        $res  = db('order')
            ->field('order.order_id,order.ification,order.order_no,co.dep_money,st.dep,be.tail,co.weixin')
            ->join('contract co', 'order.contract_id=co.contract_id', 'left')
            ->join('startup st', 'order.startup_id=st.startup_id', 'left')
            ->join('before be', 'order.before_id=be.before_id', 'left')
            ->where(['order_id' => $order_id])
            ->find();
        $thro = db('through')->where(['order_ids' => $order_id, 'baocun' => 1])->order('th_time desc')->find();
        if ($thro['baocun'] == 1) {
            $amount = $thro['amount'];
        } else {
            if ($res['ification'] == 2) {
                if ($thro) {
                    $ca = db('envelopes')->where(['through_id' => $thro['through_id']])->field('give_money')->find();
                } else {
                    $ca = db('envelopes')->where(['ordesr_id' => $order_id, 'through_id' => 0])->field('give_money')->find();
                }
                $amount = db('capital')->where(['ordesr_id' => $order_id, 'types' => 1, 'enable' => 1])->sum('to_price');
            }else {
                $ca = db('capital')->where(['ordesr_id' => $order_id, 'types' => 1, 'enable' => 1])->field('sum(to_price),sum(give_money)')->find();
              
            }
        }
        $p=$amount+$ca['expense']-$ca['give_money'];
        $yu = 0;

        if (!empty($res['dep_money']) || $res['dep_money'] == 0) {
            $yu = $p - $res['dep_money'];
        }
        if (!empty($res['dep']) && !empty($res['dep_money'])) {
            $yu = $p - $res['dep_money'] - $res['dep'];
        }
        if (!empty($res['dep']) && !empty($res['dep_money']) && !empty($res['tail'])) {
            $yu = $p - $res['dep_money'] - $res['dep'] - $res['tail'];
        }
        $cash   = 0;
        $WeChat = 0;

        if ($yu > 0) {
            $pa = db('payment')->where(['orders_id' => $order_id])->select();
            foreach ($pa as $kl) {
                if ($kl['weixin']  != 2) {
                    $cash += $kl['money'];
                }
                if ($kl['success'] == 2 && $kl['weixin'] == 2) {
                    $WeChat += $kl['money'];
                }
            }
            if (!empty($cash)) {
                $yu = $yu - $cash;
                $yu = round($yu, 3);
            }
            if (!empty($WeChat)) {
                $yu = $yu - $WeChat;
                $yu = round($yu, 3);
            }

        }

        if ($data = Request::instance()->post()) {
            if ($data['dep'] > $yu) {
                return json_data([], 300, '请输入正确的价格');
            }
            if ($data['pay_types'] == 1) {
                if (empty($data['logo'])) {
                    return json_data([], 300, '请上传图片');
                }
                $logo = serialize($data['logo']);
            } else {
                $logo = '';
            }
            $o  = [
                'money'     => $data['dep'],
                'logos'     => $logo,
                'orders_id' => $data['order_id'],
                'weixin'    => $data['pay_types'],
                'uptime'    => time(),
            ];
            $re = db('payment')->insertGetId($o);
            if ($re) {
                $this->log('支付了一笔钱', $data['order_id']);
                return json_data([], 200, '新增成功');
            }
            return json_data([], 300, '失败');
        }

        return $this->fetch('she', ['order_id' => $order_id, 'p' => $yu]);

    }

    /**
     * 确认验收
     */
    public function yan($order_id)
    {

    }


    /**
     * 订单详情
     * ac.score as pin,ac.content as fankui,
     */
    public function info($order_id = 0)
    {

        if (!$order_id) {
            $this->error('请刷新后重试');
        }
        $admin   =$this->check_authority();
        $res            = db('order')
            ->field('order.*,u.username,u.store_id,b.*,p.province,c.city,y.county,co.*,st.*,be.*,be.uptime as uptimes,ku.*,cy.residential_id,cy.management,re.content as content1,channel.title as channel_title')
            ->join('chanel b', 'order.channel_id=b.id', 'left')
            ->join('channel_details channel', 'order.channel_details=channel.id', 'left')
            ->join('user u', 'order.assignor=u.user_id ', 'left')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->join('contract co', 'order.contract_id=co.contract_id', 'left')
            ->join('startup st', 'order.startup_id=st.startup_id', 'left')
            ->join('kup ku', 'order.kupj=ku.kup_id', 'left')
            ->join('before be', 'order.before_id=be.before_id', 'left')
            ->join('community cy', 'order.order_id=cy.id', 'left')
            ->join('residential re', 're.residential_id=cy.residential_id', 'left')
            ->where(['order_id' => $order_id])
            ->find();
        $res['pro_id']  = !empty($this->t($res['pro_id'])) ? $this->t($res['pro_id']) : '暂无数据';
        $res['pro_id1'] = !empty($this->t($res['pro_id1'])) ? $this->t($res['pro_id1']) : '暂无数据';
        $res['pro_id2'] = !empty($this->t($res['pro_id2'])) ? $this->t($res['pro_id2']) : '暂无数据';

        $timediff = $res['up_time'] - $res['sta_time'];


        $res['shichang'] = $this->Sec2Time($timediff);

        $res['states'] = $this->type($res['state']);

        if (!$res) {
            $this->error('未找到该需求');
        }

        if ($res['logo']) {
            $res['logo'] = unserialize($res['logo']);
        }

        if ($res['tupian']) {
            $res['tupian'] = unserialize($res['tupian']);
        }
        if ($res['logos']) {
            $res['logos'] = unserialize($res['logos']);
        }

        if ($res['contract']) {
            $res['contract'] = unserialize($res['contract']);
        }

        if ($res['deposit']) {
            $res['deposit'] = unserialize($res['deposit']);
        }
        if ($res['invoice']) {
            $res['invoice'] = unserialize($res['invoice']);
        }
        if ($res['handover']) {
            $res['handover'] = unserialize($res['handover']);
        }
        //师傅详情;
        $shi['ids']           = $res['xiu_id'];
        $shi['sort_store_id'] = $res['store_id'];
        if (!empty($shi['ids'])) {
            $results = send_post(UIP_SRC . "/support-v1/user/old-list?ids=" . $shi['ids'] . '&sort_store_id=' . $shi['sort_store_id'], [], 2);
            $results = json_decode($results, true);
            if ($results['code'] == 200) {
                $res['shi'] = object_array($results['data']);
            } else {
                $res['shi'] = '';
            }
        } else {
            $res['shi'] = '';
        }
        $thro = db('through')->where(['order_ids' => $res['order_id'], 'baocun' => 1])->order('th_time desc')->find();
        if ($res['ification'] == 1) {
            $capital = db('capital')->where(['ordesr_id' => $res['order_id'], 'types' => 1, 'enable' => 1])->select();
            if ($capital) {
                if ($capital[0]['capitalgo']) {
                    $capitalgo = unserialize($capital[0]['capitalgo']);
                } else {
                    $capitalgo = '';
                }
                $give_d = $capital[0]['give_a'] . "\r\n" . $capital[0]['give_b'];
                if ($give_d) {
                    $give_d = !empty($give_d) ? $give_d : '';
                } else {
                    $give_d = '';
                }
                $gong         = $capital[0]['gong'];
                $give_remarks = !empty($capital[0]['give_remarks']) ? $capital[0]['give_remarks'] : '';

            } else {
                $capitalgo    = '';
                $give_d       = '';
                $gong         = 0;
                $give_remarks = '';
            }
            $cap = array_sum(array_column($capital, 'to_price'));
            $c   = array_sum(array_column($capital, 'give_money'));
            $expense = 0;
            $purchasing_discount=0;
            $purchasing_expense=0;


        } else {
            if ($thro) {
                $envelopes = db('envelopes')->where(['through_id' => $thro['through_id']])->find();
            } else {
                $envelopes = db('envelopes')->where(['ordesr_id' => $res['order_id'], 'through_id' => 0])->find();
            }
            $capital = db('capital')->where(['ordesr_id' => $res['order_id'], 'types' => 1, 'enable' => 1])->select();
            if ($envelopes['capitalgo']) {
                $capitalgo = unserialize($envelopes['capitalgo']);
            } else {
                $capitalgo = '';
            }
            $res['wen_a'] = $envelopes['wen_a'];
            $give_d       = $envelopes['give_b'];
            $c            = $envelopes['give_money'];
            $purchasing_discount            = $envelopes['purchasing_discount'];
            $purchasing_expense           = $envelopes['purchasing_expense'];
            $gong         = $envelopes['gong'];
            $give_remarks = $envelopes['give_remarks'];
            $expense = $envelopes['expense'];
            $cap          = array_sum(array_column($capital, 'to_price'));
        }

        if ($thro['baocun'] == 1) {
            $res['totalprice'] = $thro['amount']+$expense - $c;
            $res['ok']         = 2;
        } else {
            $res['totalprice'] = $cap+$expense - $res['discount'] - $res['artificial'] - $res['material'] - $c;;
            $res['ok'] = 1;
        }
        //遠程溝通

        $through        = db('through')->where(['order_ids' => $res['order_id'], 'baocun' => 0, 'capital_id' => ['eq', ' ']])->order('th_time desc')->paginate(50)
            ->each(function ($item, $key) {
                if ($item['gid']) {
                    //师傅详情;
                    $shi['ids'] = $item['gid'];
                    $results    = send_post(UIP_SRC . "/support-v1/user/old-list", $shi);
                    $results    = json_decode($results, true);
                    if ($results['code'] == 200) {
                        if (empty($results['data'])) {
                            $item['gid'] = '';
                        } else {
                            $item['gid'] = $results['data'][0]['username'];
                        }
                    } else {
                        $item['gid'] = '';
                    }
                }
                if ($item['role'] == 1) {
                    $item['admin_id'] = db('admin')->where('admin_id', $item['admin_id'])->value('username');
                } elseif ($item['role'] == 2) {
                    $item['admin_id'] = db('user')->where('user_id', $item['admin_id'])->value('username');
                }
                $item['log'] = !empty($item['log']) ? unserialize($item['log']) : '';

                return $item;
        });
        $through1       = db('through')->where('order_ids', $res['order_id'])->where(function ($query) {
            $query->whereOr(['capital_id' => ['neq', ' '], 'baocun' => 1]);
        })->order('th_time desc')->paginate(50)
            ->each(function ($item, $key) {
                if ($item['gid']) {
                    //师傅详情;
                    $shi['user_id'] = $item['gid'];
                    $results        = send_post(UIP_SRC . "/shopowner/User/searchUserId", $shi);
                    $results        = json_decode($results);
                    if ($results->code == 200) {
                        $item['gid'] = object_array($results->data);
                    } else {
                        $item['gid'] = '';
                    }
                }
                if ($item['role'] == 1) {
                    $item['admin_id'] = db('admin')->where('admin_id', $item['admin_id'])->value('username');
                } elseif ($item['role'] == 2) {
                    $item['admin_id'] = db('user')->where('user_id', $item['admin_id'])->value('username');
                }


                return $item;

            });
        $cash           = 0;
        $WeChat         = 0;
        $res['payment'] = db('payment')->where('orders_id', $res['order_id'])->select();
        $res['product'] = db('product')->where(['orders_id'=>$res['order_id']])->select();;
        if ($res['payment']) {
            foreach ($res['payment'] as $k => $v) {
                //new  app\api\model\Approval()
                $Approval=new Approval();
                if ($v['weixin']  != 2) {
                    $res['payment'][$k]['payment']  =array_values($Approval->filter_by_value($this->PaymentMethod(2), 'id', $v['weixin']))[0]['title'];
                    $res['payment'][$k]['payment1'] = 1;
                    $cash                           += $v['money'];
                } else if ($v['weixin'] == 2 ) {
                    if( $v['success'] == 2){
                        $res['payment'][$k]['payment']  = '*微信*已收款';
                    }else{
                        $res['payment'][$k]['payment']  = '*微信*未收款';
                    }
                    $WeChat                         += $v['money'];
                  
                    $res['payment'][$k]['payment1'] = 1;
                }
                if ($v['logos']) {
                    $res['payment'][$k]['logos'] = unserialize($v['logos']);
                } else {
                    $res['payment'][$k]['logos'] = '';
                }
            }
        }
     
        $r  = array_sum([$res['dep'], $res['dep_money'], $res['tail']]);
        $r1 = array_sum([$WeChat, $cash]);
        $res['total'] = $r + $r1;
        //标签
        $label               = db('label')->where('label_id', 'in', $res['label_id'])->select();
        $cos                 = db('cost')->where('order_id', $res['order_id'])->join('admin ad', 'ad.admin_id=cost.admin_id', 'left')->field('cost.*,ad.username')->find();
        $res['customers_id'] = db('customers')->where('customers_id', $res['customers_id'])->value('username');
        $complaint=db('complaint')->where(['order_id'=>$res['order_id']])->find();
        if($complaint){
            $complaint['shopowner']  =empty($complaint['shopowner'])? [] : db('user')->where('user_id', $complaint['shopowner'])->value('username');
    
            $complaint['admins']  =empty($complaint['admin_id'])? '' : db('admin')->where('admin_id', $complaint['admin_id'])->value('username');
            
            if (!empty($complaint['masterworker'])) {
                $complaint['masterworker']=empty($complaint['masterworker'])? '' :Db::connect(config('database.db2'))->table('app_user')->whereIn('id', explode(',', $complaint['masterworker']))->select();
            } else{
                $list['masterworker']=[];
            }
            $complaint['picture']=empty($complaint['picture'])? [] : unserialize($complaint['picture']);
        }
        $p               = db('sign')->where('order_id', $res['order_id'])->find();
        return $this->fetch('info', ['data' => $res, 'capital' => $capital, 'label' => $label, 'through' => $through, 'through1' => $through1, 'give_d' => $give_d, 'gong' => $gong, 'c' => $c, 'expense'=>$expense,'capitalgo' => $capitalgo, 'give_remarks' => $give_remarks, 'cos' => $cos,'complaint' => $complaint,'sign'=>$p,'hide'=>$admin['hide'],'purchasing_discount'=>$purchasing_discount,'purchasing_expense'=>$purchasing_expense]);
    }


    /***
     * @return false|\PDOStatement|string|\think\Collection
     * 问题
     */
    private function t($res)
    {
        return db('goods_category')->where(['id' => $res, 'pro_type' => 1])->value('title');
    }

    /*
      *问题
     */
    public function goods_category()
    {
        $parent_id = Request::instance()->post('parent_id');

        if ($parent_id == 0) {
            $list = db('goods_category')->where(['parent_id' => 0, 'pro_type' => 1])->select();
        } else {
            $list = db('goods_category')->where(['parent_id' => $parent_id, 'pro_type' => 1])->select();

        }

        foreach ($list as $k => $item) {
            if (!empty($item['unit_id'])) {
                $l                  = db('unit')->where(['id' => $item['unit_id']])->find();
                $list[$k]['titles'] = $l['title'];
            } else {
                $list[$k]['titles'] = '';
            }
        }

        return $list;
    }

    /**
     *远程跟进标签
     */
    public function remote()
    {
        $parent_id = Request::instance()->post('parent_id');

        if ($parent_id == 0) {
            $list = db('remote')->where(['parent_id' => 0, 'is_enable' => 1])->select();
        } else {
            $list = db('remote')->where(['parent_id' => $parent_id, 'is_enable' => 1])->select();

        }
        return $list;
    }

    public function detailed()
    {
        $parent_id = Request::instance()->post('detaileds_id');


        $list = db('detailed')->where(['detaileds_id' => $parent_id])->select();
        foreach ($list as $k => $item) {
            if (!empty($item['un_id'])) {
                $l                  = db('unit')->where(['id' => $item['un_id']])->find();
                $list[$k]['titles'] = $l['title'];
            } else {
                $list[$k]['titles'] = '';
            }
        }

        return $list;
    }

    /*
     * 查看视频，图片
     */
    public function jin($order_id)
    {
        //师傅节点视频;
        $results = send_post(UIP_SRC . "/support-v1/node/list?order_id=" . $order_id, [], 2);
        $results = json_decode($results);
        if ($results->code == 200) {
            $list = $results->data;
            $list = json_decode(json_encode($list), true);

        } else {
            $list = [];
        }

        return $this->fetch('jin', ['data' => $list]);
    }

    /**
     * 单个项目
     */
    public function detailed_dan()
    {
        $parent_id      = Request::instance()->post('detaileds_id');
        $list           = db('detailed')->where(['detailed_id' => $parent_id])->find();
        $l              = db('unit')->where(['id' => $list['un_id']])->find();
        $list['titles'] = $l['title'];


        return $list;
    }

    /**
     * 套餐
     */
    public function product_chan()
    {
        $product_id = Request::instance()->post('product_id');
        $list       = db('product_chan')->where(['parents_id' => $product_id, 'pro_types' => 1])->select();
        foreach ($list as $k => $item) {
            if (!empty($item['units_id'])) {
                $l                  = db('unit')->where(['id' => $item['units_id']])->find();
                $list[$k]['titles'] = $l['title'];
            } else {
                $list[$k]['titles'] = '';
            }
        }

        return $list;
    }

    public function product_chan_dan()
    {
        $product_id = Request::instance()->post('product_id');


        $list = db('product_chan')->where(['product_id' => $product_id, 'pro_types' => 1])->find();

        $l              = db('unit')->where(['id' => $list['units_id']])->find();
        $list['titles'] = $l['title'];
        return $list;
    }

    /***
     * @return false|\PDOStatement|string|\think\Collection
     * 指派
     */
    public function zhi($order_id, $key)
    {

        if ($data = Request::instance()->post()) {
            $user = db('user')->where('user_id', $data['user_id'])->value('state');
            if ($user != 1) {
                return json_data([], 300, '该用户离线，无法指派');
            }
            try {
                if ($data['key'] == 1) {
                    $res = db('order')->where(['order_id' => $data['order_id']])->update(['state' => 1, 'update_time' => time(), 'assignor' => $data['user_id']]);
                    db('remind')->insertGetId([
                        'admin_id' => $data['user_id'],
                        'order_id' => $data['order_id'],
                        'time'     => time(),
                        'stater'   => 1,
                        'tai'      => 1,
                    ]);
                } else {
                    $res = db('order')->where(['order_id' => $data['order_id']])->update(['update_time' => time(), 'assignor' => $data['user_id']]);
                    db('message')->where(['order_id' => $data['order_id']])->update(['already' => 0, 'have' => time()]);
                    db('remind')->where(['order_id' =>$data['order_id']])->update(['tai' => 0]);
                }
                if ($res) {

                    $li = db('order')
                        ->field('order.*,st.store_id,st.store_name,us.*,p.province,c.city,y.county')
                        ->join('user us', 'order.assignor=us.user_id', 'left')
                        ->join('store st', 'us.store_id=st.store_id', 'left')
                        ->join('province p', 'order.province_id=p.province_id', 'left')
                        ->join('city c', 'order.city_id=c.city_id', 'left')
                        ->join('county y', 'order.county_id=y.county_id', 'left')
                        ->where(['order.order_id' => $data['order_id']])
                        ->find();

                    vendor('foxyzeng.huyi.HuYiSMS');
                    $s   = $li['province'] . $li['city'] . $li['county'] . $li['addres'];
                    $sms = new HuYiSMS();
                    $new = new Jpush();

                    if (empty($li['registrationId'])) {
                        return json_data([], 300, '该用户没有登录APP');
                    }
//                $content = "尊敬的{$li['username']}店长您好！订单{$li['order_no']}来了，请尽快联系客户{$li['telephone']}预约上门服务。如有任何问题都可致电4000-987-009,回T退订【益鸟维修】";
                    $content = "尊敬的{$li['username']}店长您好！客户:{$li['contacts']}，地址:{$s}，电话:{$li['telephone']}，订单：{$li['order_no']}来了，请尽快联系客户预约上门服务。如有任何问题都可致电4000-987-009,回T退订";
                    $data    = ['order_id' => $li['order_id'], 'content' => $content, 'type' => 6, 'user_id' => $li['assignor']];
                    $new->tui('', $li['registrationId'], $data);
                    $sms->send($li['mobile'], $content);

//                    $contens = "亲，我们已经收到您在益鸟的订单，{$li['username']}店长工程师，工号:{$li['number']}，联系电话{$li['mobile']}会及时与您联系，确定上门时间哟，注意接听来电哦~~若未收到来电，请及时致电：4000987009，回T退订【益鸟维修】";
                    $contens = "亲，我们已经收到您在益鸟的订单，稍后会有专业工程师与您联系，确定上门时间哟，注意接听来电哦~~若未收到来电，请及时致电：4000987009 回T退订【益鸟维修】";
                    // $sms->duan($li['telephone'], $contens);
                    $u = $this->check_authority();
                    db("assignment")->insertGetId(['order_id' => $li['order_id'], 'admin_id' => $u['admin_id'], 'user_id' => $li['assignor'], 'time' => time()]);
                    $this->log('给' . $li['username'] . '指派一个单子', $data['order_id']);

                    return json_data([], 200, '指派成功');

                }


            } catch (Exception $e) {
                return json_data([], 300, $e->getMessage());
            }


        }
        if (!$order_id) {
            $this->error('请刷新后重试');
        }
        $user  = $this->check_authority();
        $model = db('user');
        if (!empty($user['store_id'])) {
            $model->where(['store_id' => $user['store_id']]);
        }
        $list = $model->where(['status' => 0])->order('user.created_time desc')
            ->paginate(10)
            ->each(function ($item, $key) {
                if ($item['store_id']) {
                    $li                 = db('store')->where(['store_id' => $item['store_id']])
                        ->join('province p', 'store.province=p.province_id', 'left')
                        ->join('city c', 'store.city=c.city_id', 'left')
                        ->join('county y', 'store.area=y.county_id', 'left')
                        ->field('store.store_name,store.addres,p.province ,c.city ,y.county')
                        ->find();
                    $item['store_name'] = $li['store_name'];
                    $item['province']   = $li['province'];
                    $item['city']       = $li['city'];
                    $item['area']       = $li['county'];
                    $item['addres']     = $li['addres'];
                    return $item;
                }
            });
        return $this->fetch('zhi', ['list' => $list, 'order_id' => $order_id, 'kp' => $key]);

    }

    /***
     * @return false|\PDOStatement|string|\think\Collection
     * 接单提醒
     */
    public function jie()
    {
        if ($data = Request::instance()->post()) {

            $li = db('order')
                ->field('order.*,st.store_id,st.store_name,us.*,p.province,c.city,y.county')
                ->join('user us', 'order.assignor=us.user_id', 'left')
                ->join('store st', 'us.store_id=st.store_id', 'left')
                ->join('province p', 'order.province_id=p.province_id', 'left')
                ->join('city c', 'order.city_id=c.city_id', 'left')
                ->join('county y', 'order.county_id=y.county_id', 'left')
                ->where(['order.order_id' => $data['order_id']])
                ->find();
            vendor('foxyzeng.huyi.HuYiSMS');
            $s       = $li['province'] . $li['city'] . $li['county'] . $li['addres'];
            $sms     = new HuYiSMS();
            $content = "亲，{$li['store_name']}来了一个单子，联系电话:{$li['telephone']}，用户姓名:{$li['contacts']}，居住地址:{$s}，火速联系!";

            try {

                $sms->send($li['mobile'], $content);
            } catch (Exception $e) {
                return json_data([], 300, $e->getMessage());
            }
        }
        return $this->fetch('jie');
    }

    /***
     * @return false|\PDOStatement|string|\think\Collection
     * 订单跟进
     */
    public function genadd()
    {
        if ($data = Request::instance()->post()) {
            $ification = db('order')->where(['order_id' => $data['order_ids']])->field('assignor')->find();
            //if (empty($ification['assignor'])) {
            //  return json_data([], 300, '请指派店长');
            // }
            db()->startTrans();
            if ($data['baocun'] == 1) {
                if (empty($data['amount'])) {
                    return json_data([], 300, '请添加基建');
                }
            } else {
                if (empty($data['remar'])) {
                    return json_data([], 300, '输入备注');
                }
            }

            $s = '';
            if (!empty($data['kk'])) {
                foreach ($data['kk'] as $item) {
                    $s .= $item . ',';
                }
                $s = substr($s, 0, -1);  //利用字符串截取函数消除最后一个逗号
            }
            $user = $this->check_authority();
            if ($data['type'] == 1) {
                if ($data['single'] == 1) {
                    if (empty($data['user'])) {
                        return json_data([], 300, '请输入转派人');
                    }
                }
                $t = [
                    'mode'       => $data['mode'],
                    'amount'     => 0,
                    'remar'      => $data['remar'],
                    'order_ids'  => $data['order_ids'],
                    'baocun'     => 0,
                    'role'       => 1,
                    'admin_id'   => $user['admin_id'],
                    'status'     => $this->remo($data['status']),
                    'status1'    => $this->remo($data['status1']),
                    'status2'    => $this->remo($data['status2']),
                    'th_time'    => strtotime($data['start_time']),
                    'end_time'   => strtotime($data['end_time']),
                    'single'     => $data['single'],
                    'user'       => $data['user'],
                    'capital_id' => '',//图片
                ];
            } elseif ($data['type'] == 2) {
                $t = [
                    'mode'       => $data['mode'],
                    'amount'     => $data['amount'],
                    'remar'      => $data['remar'],
                    'order_ids'  => $data['order_ids'],
                    'baocun'     => $data['baocun'],
                    'role'       => 1,
                    'admin_id'   => $user['admin_id'],
                    'status'     => '',
                    'status1'    => '',
                    'status2'    => '',
                    'th_time'    => strtotime($data['start_time']),
                    'end_time'   => strtotime($data['end_time']),
                    'single'     => '',
                    'user'       => '',
                    'capital_id' => !empty($s) ? $s : '',//图片
                ];
            }

            $res = db('through')->insertGetId($t);

            $d  = db('through')->where('order_ids', $data['order_ids'])->select();
            $s1 = '';
            foreach ($d as $item) {
                $s1 .= $item['through_id'] . ',';
            }
            $s1 = substr($s1, 0, -1);  //利用字符串截取函数消除最后一个逗号
            if ($res) {
                if ($data['baocun'] == 1) {
                    db('order')->where(['order_id' => $data['order_ids']])->update(['state' => 3, 'through_id' => $s1, 'update_time' => time()]);
                    remind($data['order_ids'], 3);
                } elseif ($data['baocun'] == 0) {
                    if ($data['state'] < 3) {
                        if (!empty($s)) {
                            db('capital')->where(['capital_id' => ['in', $s]])->update(['enable' => 0]);
                        }
                    }
                    db('order')->where(['order_id' => $data['order_ids']])->update(['through_id' => $s1, 'update_time' => time()]);
                }
                if ($data['type'] == 1) {
                    if ($data['single'] == 1) {
                        if ($data['baocun'] != 1) {
                            if (!empty($ification['assignor'])) {
                                db('order')->where(['order_id' => $data['order_ids']])->update(['update_time' => time(), 'assignor' => $data['user']]);
                                db('message')->where(['order_id' => $data['order_ids']])->update(['already' => 0, 'have' => time()]);
                                db('remind')->where(['order_id' =>$data['order_ids']])->update(['tai' => 0]);
                            } else {
                                db('order')->where(['order_id' => $data['order_ids']])->update(['update_time' => time(), 'state' => 1, 'assignor' => $data['user']]);
                                db('message')->where(['order_id' => $data['order_ids']])->update(['already' => 0, 'have' => time()]);
                                db('remind')->where(['order_id' =>$data['order_ids']])->update(['tai' => 0]);
                            }
                            $li = db('order')->field('order.*,st.store_id,st.store_name,us.*,us.state as states1,p.province,c.city,y.county')
                                ->join('user us', 'order.assignor=us.user_id', 'left')
                                ->join('store st', 'us.store_id=st.store_id', 'left')
                                ->join('province p', 'order.province_id=p.province_id', 'left')
                                ->join('city c', 'order.city_id=c.city_id', 'left')
                                ->join('county y', 'order.county_id=y.county_id', 'left')
                                ->where(['order.order_id' => $data['order_ids']])
                                ->find();
                            if ($li['states1'] != 1) {
                                db()->rollback();
                                return json_data([], 300, '该用户离线，无法指派');
                            }
                            if (empty($li['registrationId'])) {
                                return json_data([], 300, '该用户没有登录APP');
                            }
                            vendor('foxyzeng.huyi.HuYiSMS');
                            if ($data['baocun'] == 1 && $data['single'] == 1) {
                                $this->log('指派一个单子并成交了该订单', $data['order_ids']);
                            } elseif ($data['baocun'] == 1) {
                                $this->log('添加了记录并成交了该订单', $data['order_ids']);

                            } elseif ($data['single'] == 1) {
                                $this->log('指派一个单子并保存了沟通记录', $data['order_ids']);
                            } elseif ($data['single'] == 0) {
                                $this->log('保存了沟通记录', $data['order_ids']);
                            }
                            $s       = $li['province'] . $li['city'] . $li['county'] . $li['addres'];
                            $sms     = new HuYiSMS();
                            $content = "尊敬的{$li['username']}店长您好！客户:{$li['contacts']}，地址:{$s}，电话:{$li['telephone']}，订单：{$li['order_no']}来了，请尽快联系客户预约上门服务。如有任何问题都可致电4000-987-009,回T退订";
                            $new     = new Jpush();
                            $da      = ['order_id' => $li['order_id'], 'content' => $content, 'user_id' => $li['assignor'], 'type' => 6];
                            $new->tui('', $li['registrationId'], $da);
                            $content2 = "尊敬的{$li['username']}店长您好！客户:{$li['contacts']}，地址:{$s}，电话:{$li['telephone']}，订单：{$li['order_no']}来了，请尽快联系客户预约上门服务";
                            $sms->send($li['mobile'], $content);
                            $contens = "亲，我们已经收到您在益鸟的订单，{$li['username']}店长工程师，工号:{$li['number']}，联系电话{$li['mobile']}会及时与您联系，确定上门时间哟，注意接听来电哦~~若未收到来电，请及时致电：4000987009，回T退订【益鸟维修】";

                            $sms->duan($li['telephone'], $contens);
                        }
                    }
                }
                db()->commit();
                return json_data([], 200, '成功');
            }
            db()->rollback();
            return json_data([], 300, '失败');
        }
        $order_id = Request::instance()->get('order_id');
        $type     = Request::instance()->get('type');

        $chanel  = db('chanel')->select();
        $l       = db('order')->where(['order_id' => $order_id])->field('state')->find();
        $capital = db('capital')->where(['ordesr_id' => $order_id, 'enable' => 1, 'types' => 1, 'programme' => 3])->select();
        if (!empty($capital)) {
            $flag = true;
        } else {
            $flag = false;
        }
        $cap    = db('capital')->where(['ordesr_id' => $order_id, 'enable' => 1, 'types' => 1])->sum('to_price');
        $user   = db('user')->where(['status' => 0])->field('user_id,username')->select();
        $remote = db('remote')->where(['is_enable' => 1, 'parent_id' => 0])->field('id,title')->select();
        return $this->fetch('genadd', ['chanel' => $chanel, 'capital' => $capital, 'order_id' => $order_id, 'cap' => $cap, 'flag' => $flag, 'l' => $l, 'user' => $user, 'remote' => $remote, 'type' => $type]);
    }

    /**
     * 沟通记录报价单
     */
    public function bao($through_id = 0, $state)
    {
        $through = db('through')->where('through_id', $through_id)->field('capital_id,through_id,baocun,order_ids')->find();

        if ($through['capital_id']) {
            $chanel = db('capital')->where(['capital_id' => ['in', $through['capital_id']], 'types' => 1])->field('class_a,class_b,company,square,un_Price,to_price,zhi,capital_id')->select();

        } else {
            $chanel = db('capital')->where(['ordesr_id' => $through['order_ids'], 'types' => 1])->field('class_a,class_b,company,square,un_Price,to_price,zhi,capital_id')->select();
        }
        $envelopes = db('envelopes')->where(['through_id' => $through['through_id']])->find();
        if (!empty($chanel)) {
            $flag = true;
        } else {
            $flag = false;
        }
        $cap = array_sum(array_column($chanel, 'to_price'));

        return $this->fetch('bao', ['chanel' => $chanel, 'envelopes' => $envelopes, 'cap' => $cap, 'flag' => $flag, 'through_id' => $through['through_id'], 'baocun' => $through['baocun'], 'state' => $state, 'order_id' => $through['order_ids']]);


    }

    /***
     * @return false|\PDOStatement|string|\think\Collection
     * 订单跟进
     */
    public function ertao($order_id = 0)
    {


    }

    /***
     * @return false|\PDOStatement|string|\think\Collection
     * 订单回访
     */
    public function hui($order_id = 0)
    {
        if ($data = Request::instance()->post()) {


            try {

                if ($data['connect'] == 1) {

                    $hui = [

                        'uptime'       => time(),
                        'content'      => $data['content'],
                        'score'        => $data['score'],
                        'full'         => $data['full'],
                        'orders_id'    => $data['order_id'],
                        'people'       => $data['people'],
                        'dissatisfied' => $data['dissatisfied'],
                        'best'         => $data['best'],
                        'connect'      => "是",

                    ];
                } elseif ($data['connect'] == 0) {
                    $hui = [

                        'uptime'       => time(),
                        'content'      => '',
                        'score'        => 0,
                        'full'         => '',
                        'orders_id'    => $data['order_id'],
                        'people'       => $data['people'],
                        'dissatisfied' => '',
                        'best'         => '',
                        'connect'      => "否",

                    ];
                }

                $res = db("product")->insertGetId($hui);
                db('order')->where(['order_id' => $data['order_id']])->update(['product_id' => $res]);

                $this->log('回访订单', $data['order_id']);
                db()->commit();
                return json_data([], 200, '新增成功');
            } catch (Exception $e) {
                db()->rollback();
                return json_data([], 300, $e->getMessage());
            }
        }

        return $this->fetch('hui', ['data' => $order_id]);
    }

    /**
     * 确认订单
     */
    public function que($order_id)
    {
        $thro      = db('through')->where(['order_ids' => $order_id, 'baocun' => 1])->order('th_time desc')->find();
        $ification = db('order')->where(['order_id' => $order_id])->field('ification,assignor')->find();
        if (empty($ification['assignor'])) {
            return json_data([], 300, '请指派店长');
        }
        if ($ification['ification'] == 1) {
            $c = db('capital')->where(['ordesr_id' => $order_id, 'types' => 1, 'enable' => 1])->sum('give_money');
        } else {
            if ($thro) {
                $c = db('envelopes')->where(['through_id' => $thro['through_id']])->sum('give_money');
            } else {
                $c = db('envelopes')->where(['ordesr_id' => $order_id, 'through_id' => 0])->sum('give_money');
            }
        }
        $cap = db('capital')->where(['ordesr_id' => $order_id, 'types' => 1, 'enable' => 1])->sum('to_price');

        $contr            = db('contract')->where('orders_id', $order_id)->find();
        $con['logo']      = !empty($contr['contract']) ? unserialize($contr['contract']) : '';//合同;
        $con['logos']     = !empty($contr['deposit']) ? unserialize($contr['deposit']) : '';
        $con['weixin']    = $contr['weixin'];
        $con['dep_money'] = !empty($contr['dep_money']) ? $contr['dep_money'] : 0;

        if ($data = Request::instance()->post()) {
            if ($thro['baocun'] == 1) {
                if (($thro['amount'] - $data['dep_money']) < 0) {
                    return json_data([], 300, '请输入正确的价格');
                }
            } elseif (($cap - $data['dep_money']) < 0) {
                return json_data([], 300, '请输入正确的价格');
            }
            if (empty($data['weixin'])) {
                return json_data([], 300, '请选择支付方式');
            }

            if (empty($data['logo'])) {
                if ($data['weixin'] == 1 && $data['pro_types'] == 0) {
                    return json_data([], 300, '合同不能为空');
                }

            }
            if (empty($data['logos'])) {
                if ($data['weixin'] == 1) {
                    return json_data([], 300, '收据不能为空');
                }

            }

            $contract = !empty($data['logo']) ? serialize($data['logo']) : '';
            $deposit  = !empty($data['logos']) ? serialize($data['logos']) : '';

            if ($data['pro_types'] == 1) {
                $contract = '';
            }
            if (empty($data['logos']) && $data['weixin'] == 1) {
                return json_data([], 300, '发票不能为空');
            }
            db()->startTrans();
            try {
                $kl = [
                    'contract'  => $contract,
                    'con_time'  => time(),
                    'orders_id' => $data['order_id'],
                    'weixin'    => $data['weixin'],
                    'type'      => 1,
                ];
                if ($contr) {
                    db('contract')->where('orders_id', $data['order_id'])->update($kl);
                    db('order')->where(['order_id' => $data['order_id']])->update(['update_time' => time()]);
                } else {
                    $res = db('contract')->insertGetId($kl);
                    db('order')->where(['order_id' => $data['order_id']])->update(['contract_id' => $res, 'update_time' => time()]);
                }
                db('payment')
                    ->insertGetId([
                        'uptime'    => time(),
                        'logos'     => $deposit,//图片
                        'money'     => $data['dep_money'],//尾款
                        'orders_id' => $data['order_id'],
                        'weixin'    => $data['weixin'],
                    ]);
                if ($data['baocun'] == 1 && $data['weixin'] == 1) {
                    db('order')->where(['order_id' => $data['order_id']])->update(['state' => 4, 'update_time' => time()]);
                    remind($data['order_id'], 4);
                    $this->log('确认订单', $data['order_id']);
                } else {
                    db('order')->where(['order_id' => $data['order_id']])->update(['update_time' => time()]);
                }
                db()->commit();
                return json_data([], 200, '新增成功');
            } catch (Exception $e) {
                db()->rollback();
                return json_data([], 300, $e->getMessage());
            }
        }

        if ($thro['baocun'] == 1) {
            $p = $thro['amount'];

        } else {
            $p = $cap - $c;
        }

        return $this->fetch('que', ['data' => $order_id, 'p' => $p, 'contr' => $con]);
    }


    /**
     * 基建列表
     */
    public function jilie()
    {

        if ($data = Request::instance()->post()) {

            $das = json_decode($data['datas'], true);
            $da  = json_decode($data['data'], true);
            if (count($das) > 1) {
                return json_data([], 300, '赠送项目只能添加一项');
            }
            db()->startTrans();
            foreach ($da as $ke => $v) {
                if ($v['chan'] == 2) {
                    $qi_rmakes = !empty($v['qi_rmakes']) ? $v['qi_rmakes'] : '';
                } else {
                    $qi_rmakes = '';
                }

                $users = [
                    'wen_a'     => '',
                    'wen_b'     => '',
                    'wen_c'     => '',
                    'company'   => $v['company'],//单位
                    'square'    => $v['square'],//方量
                    'un_Price'  => $v['un_Price'],//单价
                    'ordesr_id' => $v['order_id'],
                    'rule'      => '',//规则
                    'zhi'       => $v['zhi'],//质保
                    'types'     => 1,//状态
                    'fen'       => $v['chan'],//状态
                    'to_price'  => $v['square'] * $v['un_Price'],//总价
                    'crtime'    => time(),
                    'class_a'   => $v['class_a'],//三
                    'class_b'   => $v['class_b'],//三
                    'qi_rmakes' => $qi_rmakes,
                    'enable'    => 1,//三
                    'programme' => 1,//三
                    'projectId' => $v['projectId'],//三
                ];
                db('capital')->insertGetId($users);

            }
            if ($das) {

                db('envelopes')->insertGetId([
                    'wen_a'        => !empty($das[0]['wen_a']) ? substr($das[0]['wen_a'], 0, -1) : '',//一级分类
                    'give_b'       => !empty($das[0]['give_b']) ? $das[0]['give_b'] : '',
                    'ordesr_id'    => $das[0]['order_id'],
                    'gong'         => $das[0]['gong'],
                    'give_remarks' => $das[0]['give_remarks'],//备注
                    'give_money'   => $das[0]['give_money'],//优惠金额
                    'capitalgo'    => !empty($das[0]['capitalgo']) ? serialize($das[0]['capitalgo']) : '',
                ]);

            }

            $pdf = new Pdf();
            $pdf = $pdf->put($data['id'], 2);
            if ($pdf) {
                db()->commit();
                return json_data([], 200);
            }
            db()->rollback();
            return json_data([], 300);
        }

        $order_id = $data = Request::instance()->get('order_id');


        return $this->fetch('jilie', ['order_id' => $order_id]);
    }

    /**
     * 基建
     */
    public function ji($order_id)
    {
        $li = db('order')
            ->join('goods_category go', 'order.pro_id=go.id')
            ->where(['order.order_id' => $order_id])
            ->find();
        $go = db('goods_category')->where(['pro_type' => 1, 'parent_id' => 0])->select();
        $gs = db('product_chan')->where(['pro_types' => 1, 'parents_id' => 0])->select();
        $po = db('detailed')->where(['detaileds_id' => 0])->select();
        $g  = db('unit')->select();
        return $this->fetch('ji', ['data' => $li, 'go' => $go, 'g' => $g, 'gs' => $gs, 'po' => $po]);
    }

    /**
     * 基建
     */
    public function zi($order_id)
    {
        $li = db('order')
            ->join('goods_category go', 'order.pro_id=go.id')
            ->where(['order.order_id' => $order_id])
            ->find();
        $go = db('goods_category')->where(['pro_type' => 1, 'parent_id' => 0])->select();
        $po = db('detailed')->where(['detaileds_id' => 0])->select();
        $g  = db('unit')->select();
        return $this->fetch('zi', ['data' => $li, 'go' => $go, 'g' => $g, 'po' => $po]);
    }

    /**
     * 远程基建
     */
    public function yuan($order_id)
    {
        if ($data = Request::instance()->post()) {

            if (empty($data['square'])) {
                return json_data([], 300, '请输入方量');
            }
            $user = [
                'wen_a'        => '',//一级分类
                'wen_b'        => '',//二
                'wen_c'        => '',//三
                'company'      => $data['company'],//单位
                'square'       => $data['square'],//方量
                'un_Price'     => $data['un_Price'],//单价
                'rule'         => $data['rule'],//规则
                'zhi'          => $data['zhi'],//质保
                'types'        => 1,//状态
                'fen'          => $data['chan'],//状态
                'to_price'     => $data['to_price'],//总价
                'capitalgo'    => '',//图片,//总价
                'crtime'       => time(),
                'ordesr_id'    => $data['order_id'],
                'give_a'       => '',//赠送项目
                'give_b'       => '',
                'gong'         => 0,
                'give_remarks' => '',//备注
                'give_money'   => '',//优惠金额
                'enable'       => 1,//三
                'programme'    => 3,//三

            ];
            if ($data['chan'] == 0) {
                $user['class_a']   = $this->orys($data['class_a']);//三
                $user['class_b']   = $this->orys($data['class_b']);//三
                $user['projectId'] = $data['class_b'];//三
            } elseif ($data['chan'] == 1) {
                $user['class_a']   = $this->ort($data['class_a']);//三
                $user['class_b']   = $this->ort($data['class_b']);//三
                $user['projectId'] = $data['class_b'];//三
            } else {
                $user['class_a']   = $data['class_a'];//三
                $user['class_b']   = '';//三
                $user['qi_rmakes'] = $data['qi_rmakes'];
                $user['company']   = $data['companys'];
                $user['un_Price']  = $data['un_Prices'];
            }
            $res = db('capital')
                ->insertGetId($user);
            if ($res) {
                return json_data([], 200, '新增成功');

            }
            return json_data([], 300, '新增成功');


        }

        $li = db('order')->where(['order.order_id' => $order_id])->find();
        $gs = db('product_chan')->where(['pro_types' => 1, 'parents_id' => 0])->select();
        $po = db('detailed')->where(['detaileds_id' => 0])->select();
        $g  = db('unit')->select();
        return $this->fetch('yuan', ['data' => $li, 'g' => $g, 'gs' => $gs, 'po' => $po]);
    }

    /**
     * 远程基建
     */
    public function zeng($order_id, $type)
    {
        if ($data = Request::instance()->post()) {

            if (empty($data['square'])) {
                return json_data([], 300, '请输入方量');
            }
            $order = db('order')->where('order_id', $data['order_id'])->field('ification,order_no')->find();
            if ($data['type'] == 2) {
                $programme = 3;
                $give_a    = '';//三
                $give_b    = '';//三
                $wen_a     = '';//一级分类
                $wen_b     = '';//二
                $wen_c     = '';//二
            } else {
                $programme = 1;
                if ($order['ification'] == 1) {
                    $capital = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1, 'programme' => 1])->order('capital_id desc')->find();
                    $give_a  = $capital['give_a'];//三
                    $give_b  = $capital['give_a'];//三
                    $wen_a   = $capital['wen_a'];//一级分类
                    $wen_b   = $capital['wen_b'];//二
                    $wen_c   = $capital['wen_c'];//二
                } else {
                    $programme = 3;
                    $give_a    = '';//三
                    $give_b    = '';//三
                    $wen_a     = '';//一级分类
                    $wen_b     = '';//二
                    $wen_c     = '';//二
                }
            }


            $user = [
                'wen_a'        => $wen_a,//一级分类
                'wen_b'        => $wen_b,//二
                'wen_c'        => $wen_c,//三
                'company'      => $data['company'],//单位
                'square'       => $data['square'],//方量
                'zhi'          => $data['zhi'],//质保
                'types'        => 1,//状态
                'fen'          => $data['chan'],//状态
                'to_price'     => $data['to_prices'],//总价
                'capitalgo'    => '',//图片,//总价
                'crtime'       => time(),
                'ordesr_id'    => $data['order_id'],
                'give_a'       => $give_a,//赠送项目
                'give_b'       => $give_b,
                'gong'         => 0,
                'give_remarks' => '',//备注
                'give_money'   => '',//优惠金额
                'enable'       => 1,//三
                'programme'    => $programme,//三


            ];
            if ($data['chan'] == 0) {
                $user['class_a']   = $this->orys($data['class_a']);//三
                $user['class_b']   = $this->orys($data['class_b']);//三
                $user['un_Price']  = $data['un_Price'];//单价
                $user['projectId'] = $data['class_b'];//三
            } elseif ($data['chan'] == 1) {
                $user['class_a']   = $this->ort($data['class_a']);//三
                $user['class_b']   = $this->ort($data['class_b']);//三
                $user['un_Price']  = $data['un_Price'];//单价
                $user['projectId'] = $data['class_b'];//三
            } else {
                $user['class_a']   = $data['class_a'];//三
                $user['class_b']   = '';//三
                $user['qi_rmakes'] = $data['qi_rmakes'];
                $user['company']   = $data['companys'];
                $user['un_Price']  = $data['un_Prices'];
            }

            $res                 = db('capital')->insertGetId($user);
            $uss                 = [];
            $po                  = [];
            $uss['order_num']    = $order['order_no'];
            $po['store_code_id'] = $res;
            $po['problem']       = '';
            $po['code']          = '';
            $po['title']         = $user['class_b'];
            $po['category']      = $user['class_a'];
            $po['unit']          = $user['un_Price'];
            $po['quantity']      = $user['square'];
            $po['price']         = $user['to_price'];
            $uss['problem']      = $po;
            Cache::set('11', $uss);
            send_post(UIP_SRC . "/shopowner/Order/editOrderProblem", $uss);
            if ($data['type'] == 2) {
                $res1 = db('capital')->where(['ordesr_id' => $data['order_id'], 'enable' => 1, 'programme' => 3, 'types' => 1])->field('capital_id,to_price')->select();
                $s    = '';
                $op   = 0;
                foreach ($res1 as $item) {
                    $s  .= $item['capital_id'] . ',';
                    $op += $item['to_price'];
                }
                $s = substr($s, 0, -1);  //利用字符串截取函数消除最后一个逗号
                db('through')->where(['order_ids' => $data['order_id'], 'baocun' => 1])->update(['capital_id' => $s, 'amount' => $op]);
            }

            if ($res) {
                return json_data([], 200, '新增成功');
            }
            return json_data([], 300, '新增成功');


        }

        $li = db('order')->where(['order_id' => $order_id])->find();
        $gs = db('product_chan')->where(['pro_types' => 1, 'parents_id' => 0])->select();
        $po = db('detailed')->where(['detaileds_id' => 0])->select();
        $g  = db('unit')->select();
        return $this->fetch('zeng', ['data' => $li, 'g' => $g, 'gs' => $gs, 'po' => $po, 'type' => $type]);
    }

    /**
     * 基建
     */
    public function edit1($order_id, $type)
    {
        if ($data = Request::instance()->post()) {
            db()->startTrans();
            try {
                if (empty($data['company'])) {
                    return json_data([], 300, '请输入单位');
                }

                if (empty($data['square'])) {
                    return json_data([], 300, '请输入方量');
                }
                $user = [
                    'company'  => $data['company'],//单位
                    'square'   => $data['square'],//方量
                    'zhi'      => $data['zhi'],//质保
                    'fen'      => $data['chan'],//状态
                    'to_price' => empty($data['to_price']) ? $data['to_prices'] : $data['to_price'],//总价
                ];
                if ($data['chan'] == 0) {
                    $user['class_a']   = $this->orys($data['class_a']);//三
                    $user['class_b']   = $this->orys($data['class_b']);//三
                    $user['un_Price']  = $data['un_Price'];//三
                    $user['projectId'] = $data['class_b'];//三
                } elseif ($data['chan'] == 1) {
                    $user['class_a']   = $this->ort($data['class_a']);//三
                    $user['class_b']   = $this->ort($data['class_b']);//三
                    $user['un_Price']  = $data['un_Price'];//三
                    $user['projectId'] = $data['class_b'];//三
                } else {
                    $user['class_a']   = '自定义项目';//三
                    $user['class_b']   = $data['class_a'];//三
                    $user['qi_rmakes'] = $data['qi_rmakes'];
                    $user['company']   = $data['companys'];
                    $user['un_Price']  = $data['un_Prices'];//三
                }
                db('capital')->where('capital_id', $data['capital_id'])->update($user);
                $uss['problem']       = '';
                $uss['code']          = '';
                $uss['store_code_id'] = $data['capital_id'];
                $uss['title']         = $user['class_b'];
                $uss['category']      = $user['class_a'];
                $uss['unit']          = $user['un_Price'];
                $uss['quantity']      = $user['square'];
                $uss['price']         = $user['to_price'];
                $da                   = send_post(UIP_SRC . "/shopowner/Order/updateOrderProblem", $uss);
                $results              = json_decode($da);
                if ($results->code != 200) {
                    db()->rollback();
                    return json_data([], 300);
                }

                $pdf = new Pdf();
                $pdf->put($data['order_id'], 1);
                db()->commit();
                return json_data([], 200, '成功');

            } catch (Exception $e) {
                db()->rollback();
                return json_data([], 300, $e->getMessage());
            }


        }
        $li  = db('capital')
            ->where(['capital_id' => $order_id, 'enable' => 1])
            ->find();
        $gs  = db('product_chan')->where(['pro_types' => 1, 'parents_id' => 0])->select();
        $po  = db('detailed')->where(['detaileds_id' => 0])->select();
        $gs2 = db('product_chan')->where(['product_title' => $li['class_a']])->field('product_id')->find();
        $po2 = db('detailed')->where(['detailed_title' => $li['class_a']])->field('detailed_id')->find();
        $gs1 = db('product_chan')->where(['parents_id' => $gs2['product_id']])->select();
        $po1 = db('detailed')->where(['detaileds_id' => $po2['detailed_id']])->select();
        $go  = db('goods_category')->where(['pro_type' => 1, 'parent_id' => 0])->select();
        $g   = db('goods_category')->where(['pro_type' => 1, 'title' => $li['wen_a']])->find();
        $go1 = db('goods_category')->where(['pro_type' => 1, 'parent_id' => $g['id']])->select();
        $g1  = db('goods_category')->where(['pro_type' => 1, 'title' => $li['wen_b']])->find();
        $go2 = db('goods_category')->where(['pro_type' => 1, 'parent_id' => $g1['id']])->select();
        $g   = db('unit')->select();
        return $this->fetch('edit1', ['data' => $li, 'go' => $go, 'go1' => $go1, 'go2' => $go2, 'g' => $g, 'gs' => $gs, 'po' => $po, 'gs1' => $gs1, 'po1' => $po1, 'type' => $type]);
    }

    /**
     * 基建
     */
    public function edit2()
    {
        if ($data = Request::instance()->post()) {
            db()->startTrans();
            try {
                if (empty($data['company'])) {
                    return json_data([], 300, '请输入单位');
                }

                if (empty($data['square'])) {
                    return json_data([], 300, '请输入方量');
                }
                $user = [
                    'company'  => $data['company'],//单位
                    'square'   => $data['square'],//方量
                    'zhi'      => $data['zhi'],//质保
                    'fen'      => $data['chan'],//状态
                    'to_price' => empty($data['to_price']) ? $data['to_prices'] : $data['to_price'],//总价
                ];
                if ($data['chan'] == 0) {
                    $user['class_a']   = $this->orys($data['class_a']);//三
                    $user['class_b']   = $this->orys($data['class_b']);//三
                    $user['un_Price']  = $data['un_Price'];//三
                    $user['projectId'] = $data['class_b'];//三
                } elseif ($data['chan'] == 1) {
                    $user['class_a']   = $this->ort($data['class_a']);//三
                    $user['class_b']   = $this->ort($data['class_b']);//三
                    $user['un_Price']  = $data['un_Price'];//三
                    $user['projectId'] = $data['class_b'];//三
                } else {
                    $user['class_a']   = '自定义项目';//三
                    $user['class_b']   = $data['class_a'];//三
                    $user['qi_rmakes'] = $data['qi_rmakes'];
                    $user['company']   = $data['companys'];
                    $user['un_Price']  = $data['un_Prices'];//三
                }
                db('capital')->where('capital_id', $data['capital_id'])->update($user);
                $WeChat = 0;
                $s      = '';
                $res1   = db('capital')->where(['ordesr_id' => $data['order_id'], 'enable' => 1, 'programme' => 3, 'types' => 1])->field('capital_id,to_price')->select();
                foreach ($res1 as $item) {
                    $WeChat += $item['to_price'];
                    $s      .= $item["capital_id"] . ',';
                }
                $s = substr($s, 0, -1);
                db('through')->where(['order_ids' => $data['order_id'], 'baocun' => 1])->update(['amount' => $WeChat, 'capital_id' => $s]);
                $uss['problem']       = '';
                $uss['code']          = '';
                $uss['store_code_id'] = $data['capital_id'];
                $uss['title']         = $user['class_b'];
                $uss['category']      = $user['class_a'];
                $uss['unit']          = $user['un_Price'];
                $uss['quantity']      = $user['square'];
                $uss['price']         = $user['to_price'];
                $da                   = send_post(UIP_SRC . "/shopowner/Order/updateOrderProblem", $uss);
                $results              = json_decode($da);
                if ($results->code != 200) {
                    db()->rollback();
                    return json_data([], 300);
                }
                db()->commit();
                return json_data([], 200, '成功');
            } catch (Exception $e) {
                db()->rollback();
                return json_data([], 300, $e->getMessage());
            }
        }
        $order_id = Request::instance()->get('order_id');
        $type     = Request::instance()->get('type');
        $li       = db('capital')
            ->where(['capital_id' => $order_id, 'types' => 1])
            ->find();

        $gs  = db('product_chan')->where(['pro_types' => 1, 'parents_id' => 0])->select();
        $po  = db('detailed')->where(['detaileds_id' => 0])->select();
        $gs2 = db('product_chan')->where(['product_title' => $li['class_a']])->field('product_id')->find();
        $po2 = db('detailed')->where(['detailed_title' => $li['class_a']])->field('detailed_id')->find();
        $gs1 = db('product_chan')->where(['parents_id' => $gs2['product_id']])->select();

        $po1 = db('detailed')->where(['detaileds_id' => $po2['detailed_id']])->select();
        $g   = db('unit')->select();
        return $this->fetch('edit2', ['data' => $li, 'g' => $g, 'gs' => $gs, 'po' => $po, 'gs1' => $gs1, 'po1' => $po1, 'through_id' => $type]);
    }

   

    /**
     * 修改公共
     */
    public function gong($order_id)
    {

    }

    /**
     * 基建
     */
    public function xia()
    {
        $data = Request::instance()->post();
        $usr  = db('order')->where(['order_id' => $data['order']])->field('assignor')->find();
        $us   = db('user')->where(['user_id' => $usr['assignor']])->field('number')->find();
        $or2  = db('sign')->where(['user_id' => $usr['assignor']])->order('sign_id desc')->field('contract')->find();
        if ($or2) {
            $hello = explode('-', $or2['contract'])[1];

            $contract = $us['number'] . '-' . ((int)$hello + 1);
        } else {
            $contract = $us['number'] . '-1';
        }

        $sign = [
            'idnumber' => $data['number'],
            'contract' => $contract,
            'username' => $data['username'],
            'order_id' => $data['order'],
            'user_id'  => $usr['assignor'],
            'addres'   => $data['addres'],
        ];
        $res  = db('sign')->insertGetId($sign);
        db('order')->where(['order_id' => $data['order']])->update(['online' => 2, 'update_time' => time()]);
        if ($res) {
            return json_data([], 200, '成功');

        }
        return json_data([], 300, '失败');

    }

    public function type($type)
    {
        if ($type == 0) {
            $title = "待指派";
        } elseif ($type == 1) {
            $title = "待接单";
        } elseif ($type == 2) {
            $title = "待上门";
        } elseif ($type == 3) {
            $title = "待签约";
        } elseif ($type == 5 || $type == 4) {
            $title = "施工中";
        } elseif ($type == 6) {
            $title = "已完成";
        } elseif ($type == 7) {
            $title = "已完工";
        } elseif ($type == 8) {
            $title = "已取消";
        } elseif ($type == 9) {
            $title = "退单";
        } elseif ($type == 10) {
            $title = "无效订单";
        }
        return $title;
    }

    public function Sec2Time($time)
    {
        if (is_numeric($time)) {
            $value = [
                "days"    => 0, "hours" => 0,
                "minutes" => 0, "seconds" => 0,
            ];

            if ($time >= 86400) {
                $value["days"] = floor($time / 86400);
                $time          = ($time % 86400);
            }
            if ($time >= 3600) {
                $value["hours"] = floor($time / 3600);
                $time           = ($time % 3600);
            }
            if ($time >= 60) {
                $value["minutes"] = floor($time / 60);
                $time             = ($time % 60);
            }
            $value["seconds"] = floor($time);
            //return (array) $value;
            $t = $value["days"] . "天" . " " . $value["hours"] . "小时" . $value["minutes"] . "分" . $value["seconds"] . "秒";
            return $t;
        } else {
            return (bool)FALSE;
        }
    }

    public function ory($id)
    {
        $re = db('goods_category')->where(['id' => $id])->field('title')->find();
        return $re['title'];
    }

    public function orys($id)
    {
        $re = db('product_chan')->where(['product_id' => $id])->field('product_title')->find();
        return $re['product_title'];
    }

    public function ort($id)
    {
        $re = db('detailed')->where(['detailed_id' => $id])->field('detailed_title')->find();
        return $re['detailed_title'];
    }

    public function remo($id)
    {
        $re = db('remote')->where(['id' => $id])->field('title')->find();
        return $re['title'];
    }

    /**
     * 获取后台客户注册的
     */
    public function jp()
    {
        $data = Request::instance()->post();
        db('admin')->where(['admin_id' => $data['admin_id']])->update(['jp' => 1]);
        return json_encode(['code' => 200]);

    }

    /*
    * 成本核算
    */
    public function cost()
    {
        $user = $this->check_authority();
        if ($data = Request::instance()->post()) {
            $res  = db('cost')->where('order',$data['order_id'])->find();
            if ($res) {
                return json_data([], 200, '添加成功');
            }
            $user = [
                'content'  => $data['content'],
                'type'     => $data['type'],
                'time'     => time(),
                'order_id' => $data['order_id'],
                'admin_id' => $user['admin_id'],

            ];
            $res  = db('cost')->insertGetId($user);

            if ($res) {
                return json_data([], 200, '添加成功');
            }
            return json_data([], 300, '添加失败');
        }
        $order_id = $data = Request::instance()->get('order_id');
        return $this->fetch('cost', ['data' => $order_id]);

    }

    /*
     * 成本核算修改
     */
    public function cheng()
    {
        $user = $this->check_authority();
        if ($data = Request::instance()->post()) {

            $user = [
                'content'  => $data['content'],
                'type'     => $data['type'],
                'time'     => time(),
                'order_id' => $data['order_id'],
                'admin_id' => $user['admin_id'],

            ];
            $res  = db('cost')->where(['id' => $data['id']])->update($user);

            if ($res) {
                return json_data([], 200, '编辑成功');
            }
            return json_data([], 300, '编辑失败');
        }
        $order_id = $data = Request::instance()->get('order_id');
        $res      = db('cost')->where(['id' => $order_id])->find();
        return $this->fetch('accounting', ['data' => $res]);

    }

    private function log($content, $ord_id)
    {
        $user = $this->check_authority();
        $user = [
            'admin_id'   => $user['admin_id'],
            'created_at' => time(),
            'content'    => $content,
            'ord_id'     => $ord_id,

        ];
        db('log')->insertGetId($user);
    }
    /*
       * 支付方式
       */
    public function PaymentMethod()
    {
        $Data = [['id' => 1, 'title' => '现金支付', 'type' => 1,], ['id' => 3, 'title' => '扫码支付-微信', 'type' => 3,], ['id' => 4, 'title' => '扫码支付-支付宝', 'type' => 4,], ['id' => 5, 'title' => '电商平台支付-淘宝', 'type' => 5,], ['id' => 6, 'title' => 'POS机', 'type' => 6,], ['id' => 7, 'title' => '好哒二维码', 'type' => 7,], ['id' => 8, 'title' => '银行卡', 'type' => 8,], ['id' => 0, 'title' => '', 'type' => 8], ['id' => 10, 'title' => '电商平台支付-天猫', 'type' => 10], ['id' => 11, 'title' => '电商平台支付-京东', 'type' => 11],

        ];

        return $Data;

    }
}
